package com.ddj.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.ddj.util.HibernateSessionFactory;

/**
 * @author DDJ HOST
 * 2008-8-18
 */
public class UniversalDAO {

    //用于增加或修改操作
    public void saveOrUpdate(final Object entity) {
	Session session = HibernateSessionFactory.getSession();
	Transaction tc = session.beginTransaction();

	session.saveOrUpdate(entity);

	tc.commit();
	session.close();
    }

    //用于删除操作
    public void delete(Object entity) {
	Session session = HibernateSessionFactory.getSession();
	Transaction tc = session.beginTransaction();

	session.delete(entity);

	tc.commit();
	session.close();
    }

    //用于查询操作
    public Object load(Class entityClass, Serializable id) {
	Session session = HibernateSessionFactory.getSession();

	return session.load(entityClass, id);	 
    }

    public Object get(Class entityClass, Serializable id) {
	Session session = HibernateSessionFactory.getSession();

	Object obj = session.get(entityClass, id);

	session.close();
	return obj;
    }

    //返回list的查询 用hql 查询，传入？的值,并设置查询的起始值和长度
    public List find(final String hql, final int firstResult,
	    final int maxResults, final Object[] values) {
	Session session = HibernateSessionFactory.getSession();

	Query queryObject = session.createQuery(hql);
	if (firstResult >= 0) {
	    queryObject.setFirstResult(firstResult);
	}
	if (maxResults > 0) {
	    queryObject.setMaxResults(maxResults);
	}
	if (values != null) {
	    for (int i = 0; i < values.length; i++) {
		queryObject.setParameter(i, values[i]);
	    }
	}
	List list = queryObject.list();
	return list;
    }

    public List find(final String hql, final Object[] values) {
	return find(hql, -1, -1, values);
    }

    
    public List findByValueBean(final String hql, final Object valueBean) {
	Session session = HibernateSessionFactory.getSession();

	Query queryObject = session.createQuery(hql);
	queryObject.setProperties(valueBean);
	List list = queryObject.list();
	return list;
    }
}
